package com.wk1un2.controller;

import java.util.Map;

import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.wk1un2.entity.Users;
import com.wk1un2.service.UsersService;
import com.wk1un2.util.MD5Util;
import com.wk1un2.util.Result;

@RequestMapping("/public")
@RestController
public class UsersController {
	@Autowired
	private UsersService usersservice;
	/**
	 * 查询全部用户
	 * 
	 * @param map
	 * @return
	 */
	@RequestMapping("/getAllUsers")
	public Object getAll(@RequestParam Map<String, Object> map) {
		Integer page = Integer.parseInt(map.get("page").toString());
		Integer limit = Integer.parseInt(map.get("limit").toString());
		map.put("page", (page - 1) * limit);
		map.put("limit", limit);
		Result res = new Result(0, "请求成功", usersservice.count(map), usersservice.getAllUsers(map));
		return res;
	}

//--------------------------------------------------------------------
	@RequestMapping("/login")
	public JSONObject login(Users u) {
		JSONObject jsonObject = new JSONObject();
		Users usersForBase = usersservice.getByUsersName(u.getUsername());// 此处打断点
		// Integer errorCount = 0;// 判断登录出错次数
		UsernamePasswordToken t = null;
		if (usersForBase == null) {
			jsonObject.put("success", false);
			jsonObject.put("message", "登录失败,用户不存在！");
			return jsonObject;
		} else {
			if (!MD5Util.verify(u.getUserpassword(), usersForBase.getUserpassword())) {
				// 密码不对、修改密码错误次数+1
				jsonObject.put("success", false);
				String msg;
				if (usersForBase.getPsdWrongCount() == 5) {
					usersservice.DoIsLock(usersForBase.getUserid(), 2);
					msg = "密码错误次数上限，账户已锁定！<br/>请找回密码或联系管理员重置密码。";
				} else {
					usersservice.errorcount(usersForBase.getUserid(), usersForBase.getPsdWrongCount() + 1);
					msg = "密码错误！你还有" + (5 - usersForBase.getPsdWrongCount() - 1) + "次机会！";
				}
				jsonObject.put("message", msg);
				return jsonObject;
			} else if (usersForBase.getIsLockout() == 2) {
				jsonObject.put("success", false);
				jsonObject.put("message", "登陆失败，账户已锁定！<br/>请找回密码或联系管理员重置密码。");
				return jsonObject;
			} else {
				// 登录成功吧错误密码次数改成0
			//	usersForBase
				usersservice.errorcount(usersForBase.getUserid(), usersForBase.getPsdWrongCount() -usersForBase.getPsdWrongCount() );
				try {
//					String erro=null;
					Subject subject = SecurityUtils.getSubject();
					t = new UsernamePasswordToken(usersForBase.getUsername(), usersForBase.getUserpassword());
					subject.login(t);
				} catch (AuthenticationException e) {
					// TODO: handle exception
					e.printStackTrace();
				} catch (AuthorizationException e) {
					e.printStackTrace();
				}
			}
			jsonObject.put("success", true);
			jsonObject.put("token", t);
			jsonObject.put("user", usersForBase);
			return jsonObject;
		}

	}

//------------------------------------------------------
	/**
	 * 添加用户
	 * 
	 * @param map
	 * @return
	 */
	@RequestMapping("/addUsers")
	public Object add(@RequestParam Map<String, Object> map) {
		Result res = null;
		if (usersservice.getUsersName(map.get("username").toString()) > 0) {
			res = new Result(0, "添加失败，用户姓名重复了！！！", -1, false);
		} else {
			//map.put("userpassword", MD5Util.getMD5(map.get("userpassword").toString()));
			//res = new Result(0, "请求成功", usersservice.add(map), true);
			if (map.get("userpassword").equals(map.get("rePwd"))) {
				map.put("userpassword", MD5Util.getMD5(map.get("userpassword").toString()));
				res = new Result(0, "请求成功", usersservice.add(map), true);
			}else {
				res = new Result(0, "确认密码错误", -2, false);
			}
		}
		
		return res;
	}
	/**
	 * 修改用户
	 * 
	 * @param map
	 * @return
	 */
	@RequestMapping("/updateUsers")
	public Object update(@RequestParam Map<String, Object> map) {
		Result res = new Result(0, "请求成功", usersservice.update(map), true);
		return res;
	}
	/**
	 * 删除用户
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/deleteUsers")
	public Object delete(Integer userid,Integer uid) {
		Result res = null;
		if (usersservice.getUsersRole(userid) > 0) {
			res = new Result(0, "删除失败,该用户名下分配有角色！！！", -1, false);
		} else {
			if (userid.equals(uid)) {
				res = new Result(0, "删除失败,用户不能删除自己!!", -2, false);
			}else {
			res = new Result(0, "请求成功", usersservice.delete(userid), true);
		}
			}
		return res;
	}

	/**
	 * 是否锁定用户接口
	 * 
	 * @param id
	 * @param isLockout
	 * @return
	 */
	// 修改状态
	@RequestMapping("/updateuserstate")

	public Result updateuserstate(Integer userid, Integer IsLockout) {
		usersservice.updateuserstate(userid, IsLockout);
		return Result.ok("1");
	}
	
	
	
	/**
	 * 重置密码
	 * 
	 * @param map
	 * @return
	 */
	@RequestMapping("/resetPassword")
	public Object resetPassword(@RequestParam Map<String, Object> map) {
		map.put("userpassword", MD5Util.getMD5("123456"));
		Result res = new Result(0, "请求成功", usersservice.updatepassword(map), true);
		return res;
	}
	/*
	 * @RequestMapping("updateuserstate1") public Result updateuserstate1(Integer
	 * userid, Integer IsLockout) { Result res =null; if
	 * (usersservice.updateuserstate(userid, IsLockout)>0) { res = new Result(0,
	 * "请求成功", 1, IsLockout); } else { res = new Result(1, "请求失败", -1, false); }
	 * return res; }
	 */

	
	
	
	
	
	/**
	 * 修改密码
	 * 
	 * @param map
	 * @return
	 */

	@RequestMapping("/changepassword")
	public Object changepassword(@RequestParam Map<String, Object> map) {
		// System.out.println("===>"+map);
		String old = map.get("old_password").toString();
		Users u = usersservice.getByUsersName(map.get("username").toString());
		Result res = null;
		if (!MD5Util.verify(old, u.getUserpassword())) {
			// 密码不对,修改密码错误次数+1
			String msg;
			if (u.getPsdWrongCount() == 5) {
				usersservice.DoIsLock(u.getUserid(), 1);
				msg = "原密码错误次数上限,账户以锁定!<br/>请找回密码或联系管理员重置密码。";
			} else {
				usersservice.errorcount(u.getUserid(), u.getPsdWrongCount() + 1);
				msg = "原密码错误! 你还有" + (5 - u.getPsdWrongCount() - 1) + "次机会!";
			}
			res = new Result(1, msg, -1, false);
		} else if (map.get("new_password").equals(map.get("again_password")) == false) {
			res = new Result(1, "两次输入密码不一致", -1, false);
		} else {
			map.put("userpassword", MD5Util.getMD5(map.get("new_password").toString()));
			usersservice.errorcount(u.getUserid(), 0);
			res = new Result(0, "密码修改成功", usersservice.updatepassword(map), true);
		}
		return res;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

	/**
	 * 获取全部角色
	 * 
	 * @param m
	 * @return
	 */
	@RequestMapping("/getAllBoxRoles")
	public Object getAllBoxRoles(@RequestParam Map<String, Object> map) {
		Result res = new Result(0, "true", 10, usersservice.getAllBoxRoles(map));
		return res;
	}
	/**
	 * 获取用户已有角色
	 * 
	 * @param m
	 * @return
	 */
	@RequestMapping("/getAllBoxUserRoles")
	public Object getAllBoxUserRoles(@RequestParam Map<String, Object> map) {
		Result res = new Result(0, "true", usersservice.getAllBoxUserRoles(map).size(), usersservice.getAllBoxUserRoles(map));
		return res;
	}
	/**
	 * 用户添加角色
	 * 
	 * @param m
	 * @return
	 */
	@RequestMapping("/addBoxRoles")
	public Object addBoxRoles(@RequestParam Map<String, Object> map) {
		int i = usersservice.addBoxRoles(map);
		Result res = new Result(0, "true", i, i);
		return res;
	}
	/**
	 * 删除用户角色
	 * 
	 * @param UserId
	 * @param RoleId
	 * @return
	 */
	@RequestMapping("/deleteBoxRoles")
	public Object deleteBoxRoles(@Param("userid") Integer userid,@Param("roleid") Integer roleid) {
		int i = usersservice.deleteBoxRoles(userid, roleid);
		Result res = new Result(0, "true", i, i);
		return res;
	}
	
	
	
	
	
	
	
	
	
}
	
	
	
	
	
	
	
	
	
	
